package com.wclass.controller.app;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qiniu.pili.Client;
import com.qiniu.pili.Hub;
import com.qiniu.pili.PiliException;
import com.qiniu.pili.Stream;
import com.wclass.common.DateUtil;
import com.wclass.common.ReturnObject;
import com.wclass.entity.*;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.interceptor.IgnoreAuth;
import com.wclass.model.*;
import com.wclass.service.*;
import io.rong.RongCloud;
import io.rong.models.Result;
import io.rong.models.chatroom.ChatroomModel;
import io.rong.models.group.GroupMember;
import io.rong.models.group.GroupModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程基本信息 前端控制器
 * </p>
 *
 * @author 张浩高
 * @since 2018-12-21
 */
@Api(description = "课程信息管理")
@RestController
@RequestMapping("/courseInfo")
public class CourseInfoController {

    @Autowired
    private ICourseInfoService iCourseInfoService;
    @Autowired
    private ICourseChapterService iCourseChapterService;
    @Autowired
    private ICouresProgressBillService iCouresProgressBillService;
    @Autowired
    private IBaseAppUserService iBaseAppUserService;
    @Autowired
    private ICouresOrderService iCouresOrderService;
    @Autowired
    private ICourseTypeService iCourseTypeService;
    @Autowired
    private ICouresTaskService iCouresTaskService;
    @Autowired
    private IBaseFocusService iBaseFocusService;
    @Autowired
    private IBaseCollectService iBaseCollectService;
    @Autowired
    private IBaseFeedbackService iBaseFeedbackService;
    @Autowired
    private ICourseClickService iCourseClickService;
    @Autowired
    private IBaseOrganService iBaseOrganService;
    @Autowired
    private ICourseWareService iCourseWareService;
    @Autowired
    private IBaseIdService iBaseIdService;

    /**
     * 七牛accessKey
     */
    @Value("${qiniu.accessKey}")
    private String accessKey;
    /**
     * 七牛secretKey
     */
    @Value("${qiniu.secretKey}")
    private String secretKey;
    /**
     * 七牛推流
     */
    @Value("${qiniu.APIHost.publish}")
    private String publish;
    /**
     * 七牛拉流
     */
    @Value("${qiniu.APIHost.hdl}")
    private String hdl;

    @Value("${qiniu.APIHost.rtmp}")
    private String rtmp;

    @Value("${qiniu.APIHost.hls}")
    private String hls;
    /**
     * 七牛空间
     */
    @Value("${qiniu.hubName}")
    private String hubName;
    /**
     * 融云
     */
    @Value("${rong.appKey}")
    private String appKey;
    /**
     * 融云
     */
    @Value("${rong.appSecret}")
    private String appSecret;


    @ApiOperation("获取已购买课程")
    @RequestMapping(value = "/getBuyPage", method = RequestMethod.POST)
    public ReturnObject<List<CourseInfo>> getBuyPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                     @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                     @ApiParam("付费课/免费(0:付费，1：免费)") Integer type) {
        EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
        ew.setSqlSelect(",courseOrder.evaluate_state");
        ew.orderBy("latest_study_time", false).orderBy("info.crt_time", false);
        if (type != null) {
            if (type == 1) {
                ew.eq("info.amount", 0);
            } else {
                ew.ne("info.amount", 0);
            }
        }
        ew.eq("info.audit_state", 1);
        List<Object> list = iCouresOrderService.selectObjs(
                new EntityWrapper<CouresOrder>().setSqlSelect("course_info_id")
                        .eq("pay_person_id", BaseContextHandler.getUserID()).eq("pay_state", 1)
                        .orderBy("crt_time", false));
        if (list.size() == 0) {
            return new ReturnObject<>(0, "获取成功");
        }
        ew.in("info.id", list);
        ew.eq("courseOrder.pay_person_id", BaseContextHandler.getUserID());
        Page<CourseInfo> obj = iCourseInfoService.selectCourseWithOrderPage(new Page<>(offset, limit), ew);

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("获取我的学习进度分页")
    @RequestMapping(value = "/getMyCouresProgressPage", method = RequestMethod.POST)
    public ReturnObject<Object> getMyCouresProgressPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                        @ApiParam("页数") @RequestParam(defaultValue = "1") int offset) {
        Page<Long> obj = iCouresOrderService.selectHasProcessList(new Page<>(offset, limit), BaseContextHandler.getUserID());

        List<Map<String, Object>> list = Lists.newArrayList();
        for (Long courseInfoId : obj.getRecords()) {
            Map<String, Object> map = iCouresProgressBillService.selectMapByUserIdAndCouresId(BaseContextHandler.getUserID(), courseInfoId);
            list.add(map);
        }
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), list);
    }

    @ApiOperation("获取指定学生的学习进度分页")
    @RequestMapping(value = "/getCouresProgressPageByUserId", method = RequestMethod.POST)
    public ReturnObject<Object> getCouresProgressPageByUserId(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                              @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                              @ApiParam("用户id") @RequestParam Long userId) {
        Page<Long> obj = iCouresOrderService.selectHasProcessList(new Page<>(offset, limit), userId);
        List<Map<String, Object>> list = Lists.newArrayList();
        for (Long courseInfoId : obj.getRecords()) {
            Map<String, Object> map = iCouresProgressBillService.selectMapByUserIdAndCouresId(userId, courseInfoId);
            list.add(map);
        }
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), list);
    }

    @IgnoreAuth
    @ApiOperation("获取指定老师下的课程分页")
    @RequestMapping(value = "/getCourseInfoPageByTeacherId", method = RequestMethod.POST)
    public ReturnObject<List<CourseInfo>> getCourseInfoPageByTeacherId(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                                       @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                                       @ApiParam("老师id") Long userId) {
        EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
        ew.eq("info.audit_state", 1);
        ew.eq("info.user_id", userId);
        ew.orderBy("info.crt_time");
        Page<CourseInfo> obj = iCourseInfoService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @IgnoreAuth
    @ApiOperation("获取课程分页")
    @RequestMapping(value = "/getPage", method = RequestMethod.POST)
    public ReturnObject<List<CourseInfo>> getPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                  @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                  @ApiParam("排序（综合:info.crt_time,好评：info.feedback_rate,人气:info" +
                                                          ".fixture_num,价钱:info.amount）") @RequestParam(defaultValue =
                                                          "info.crt_time") String sort,
                                                  @ApiParam("排序方式（0:正序，1:倒叙）") @RequestParam(defaultValue =
                                                          "1") Integer isAsc,
                                                  @ApiParam("播放类型（0：直播，1：点播）") Integer liveType,
                                                  @ApiParam("最低价(单位：分)") Long startAmount,
                                                  @ApiParam("最高价(单位：分)") Long endAmount,
                                                  @ApiParam("具体课程类型，传3级分类id") Long courseTypeId,
                                                  @ApiParam("全部课程类型，传2级分类id（优先筛选）") Long secCourseTypeId) {
        EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
        ew.eq("info.audit_state", 1);
        if (liveType != null) {
            ew.eq("info.live_type", liveType);
        }
        if (startAmount != null) {
            ew.ge("info.amount", startAmount);
        }
        if (endAmount != null) {
            ew.le("info.amount", endAmount);
        }
        if (secCourseTypeId != null) {
            EntityWrapper<CourseType> typeEw = new EntityWrapper<>();
            typeEw.setSqlSelect("id");
            typeEw.eq("p_id", secCourseTypeId);
            List<Object> typeIdList = iCourseTypeService.selectObjs(typeEw);
            ew.in("info.course_type_id", typeIdList);
        } else if (courseTypeId != null) {
            ew.eq("info.course_type_id", courseTypeId);
        }
        if (sort.equals("info.feedback_rate"))
            ew.orderBy("info.star", isAsc == 1 ? false : true);
        else
            ew.orderBy(sort, isAsc == 1 ? false : true);
        Page<CourseInfo> obj = iCourseInfoService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @IgnoreAuth
    @ApiOperation("获取课程分页")
    @RequestMapping(value = "/getPageInMobile", method = RequestMethod.POST)
    public ReturnObject<List<CourseInfo>> getPageInMobile(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                  @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                  @ApiParam("排序（综合:info.crt_time,好评：info.feedback_rate,人气:info" +
                                                          ".fixture_num,价钱:info.amount）") @RequestParam(defaultValue =
                                                          "info.crt_time") String sort,
                                                  @ApiParam("排序方式（0:正序，1:倒叙）") @RequestParam(defaultValue =
                                                          "1") Integer isAsc,
                                                  @ApiParam("播放类型（0：直播，1：点播）") Integer liveType,
                                                  @ApiParam("最低价(单位：分)") Long startAmount,
                                                  @ApiParam("最高价(单位：分)") Long endAmount,
                                                  @ApiParam("具体课程类型，分类id") Long courseTypeId) {
        EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
        ew.eq("info.audit_state", 1);
        if (liveType != null) {
            ew.eq("info.live_type", liveType);
        }
        if (startAmount != null) {
            ew.ge("info.amount", startAmount);
        }
        if (endAmount != null) {
            ew.le("info.amount", endAmount);
        }

        List<Object> list = Lists.newArrayList();
        getChildCourseTypeIdList(list, courseTypeId);
        ew.in("info.course_type_id", list);

        if (sort.equals("info.feedback_rate"))
            ew.orderBy("info.star", isAsc == 1 ? false : true);
        else
            ew.orderBy(sort, isAsc == 1 ? false : true);
        Page<CourseInfo> obj = iCourseInfoService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    /**
     * 获取课程分类最后一层子分类id
     * @param list
     * @param courseTypeId
     */
    public void getChildCourseTypeIdList(List<Object> list, Long courseTypeId){
        EntityWrapper<CourseType> typeEw = new EntityWrapper<>();
        typeEw.setSqlSelect("id");
        typeEw.eq("p_id", courseTypeId);
        List<Object> typeIdList = iCourseTypeService.selectObjs(typeEw);

        if (typeIdList.size() > 0) {
            for (Object typeId : typeIdList) {
                getChildCourseTypeIdList(list, Long.parseLong(typeId.toString()));
            }
        } else {
            list.add(courseTypeId);
        }
    }

    @ApiOperation("日历-老师当月课程日历打点")
    @RequestMapping(value = "/getTeacherLiveCourseMonth", method = RequestMethod.POST)
    public ReturnObject<Object> getTeacherLiveCourseMonth(@ApiParam("时间（格式yyyy-MM）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM") Date date) throws Exception {

        EntityWrapper<CourseChapter> ew = new EntityWrapper<>();
        ew.orderBy("info.start_time", false);
        ew.eq("info.user_id", BaseContextHandler.getUserID());
        ew.ge("info.start_time", DateUtil.getMonthStartTime(date));
        ew.le("info.end_time", DateUtil.getMonthEndTime(date));
        ew.ne("info.type", 3);
        List<CourseChapter> courseChapters = iCourseChapterService.selectList(ew);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        List<String> list = Lists.newArrayList();

        for (CourseChapter info : courseChapters) {
            list.add(df.format(info.getStartTime()));
        }
        return new ReturnObject<>(0, "获取成功", list);
    }

    @ApiOperation("日历-老师当月课程日历打点(PC专用)")
    @RequestMapping(value = "/getTeacherLiveCourseMonthForPC", method = RequestMethod.POST)
    public ReturnObject<Object> getTeacherLiveCourseMonthForPC(@ApiParam("时间（格式yyyy-MM）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM") Date date) throws Exception {

        EntityWrapper<CourseChapter> ew = new EntityWrapper<>();
        ew.orderBy("info.start_time", false);
        ew.eq("info.user_id", BaseContextHandler.getUserID());
        ew.ge("info.start_time", DateUtil.getMonthStartTime(date));
        ew.le("info.end_time", DateUtil.getMonthEndTime(date));
        ew.ne("info.type", 3);
        List<CourseChapter> courseChapters = iCourseChapterService.selectList(ew);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        List<Map<String, Object>> list = Lists.newArrayList();

        for (CourseChapter info : courseChapters) {
            Map<String, Object> map = Maps.newHashMap();
            map.put(df.format(info.getStartTime()), "");
            list.add(map);
        }
        return new ReturnObject<>(0, "获取成功", list);
    }


    @ApiOperation("日历-获取老师待上课课程")
    @RequestMapping(value = "/getMyWaitPage", method = RequestMethod.POST)
    public ReturnObject<List<CourseChapter>> getMyWaitPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                           @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                           @ApiParam("根据上课时间查询（yyyy-MM-dd）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        EntityWrapper<CourseChapter> ew = new EntityWrapper<>();
        ew.orderBy("info.start_time", false);
        ew.eq("info.user_id", BaseContextHandler.getUserID());
        ew.ge("info.start_time", DateUtil.getStartTime(date));
        ew.le("info.end_time", DateUtil.getEndTime(date));
        ew.ne("info.type", 3);
        Page<CourseChapter> obj = iCourseChapterService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("日历-学生当月课程日历打点")
    @RequestMapping(value = "/getLiveCourseMonth", method = RequestMethod.POST)
    public ReturnObject<Object> getLiveCourseMonth(@ApiParam("时间（格式yyyy-MM）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM") Date date) throws Exception {

        EntityWrapper<CourseChapter> ew = new EntityWrapper<>();
        ew.eq("orderinfo.user_id", BaseContextHandler.getUserID());
        ew.ge("info.start_time", DateUtil.getMonthStartTime(date));
        ew.le("info.end_time", DateUtil.getMonthEndTime(date));
        ew.ne("info.type", 3);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<CourseChapter> courseChapters = iCourseChapterService.selectList(ew);

        List<String> list = Lists.newArrayList();
        for (CourseChapter info : courseChapters) {
            list.add(df.format(info.getStartTime()));
        }
        return new ReturnObject<>(0, "获取成功", list);
    }

    @ApiOperation("日历-学生当月课程日历打点（PC端专用）")
    @RequestMapping(value = "/getLiveCourseMonthForPC", method = RequestMethod.POST)
    public ReturnObject<Object> getLiveCourseMonthForPC(@ApiParam("时间（格式yyyy-MM）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM") Date date) throws Exception {

        EntityWrapper<CourseChapter> ew = new EntityWrapper<>();
        ew.eq("orderinfo.user_id", BaseContextHandler.getUserID());
        ew.ge("info.start_time", DateUtil.getMonthStartTime(date));
        ew.le("info.end_time", DateUtil.getMonthEndTime(date));
        ew.ne("info.type", 3);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<CourseChapter> courseChapters = iCourseChapterService.selectList(ew);

        List<Map<String, Object>> list = Lists.newArrayList();
        for (CourseChapter info : courseChapters) {
            Map<String, Object> map = Maps.newHashMap();
            map.put(df.format(info.getStartTime()), "");
            list.add(map);
        }
        return new ReturnObject<>(0, "获取成功", list);
    }


    @ApiOperation("日历-获取学生我的直播课程分页")
    @RequestMapping(value = "/getStartLivePage", method = RequestMethod.POST)
    public ReturnObject<List<CourseInfo>> getStartLivePage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                           @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                           @ApiParam("时间（格式yyyy-MM-dd）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) throws Exception {

        EntityWrapper<CouresOrder> ew = new EntityWrapper<>();
        ew.eq("info.pay_person_id", BaseContextHandler.getUserID());
        ew.ge("chapter.start_time", DateUtil.getStartTime(date));
        ew.le("chapter.end_time", DateUtil.getEndTime(date));
        ew.ne("chapter.type", 3);

        Page<CouresOrder> obj = iCouresOrderService.selectPage(new Page<>(offset, limit), ew);
        List<CourseInfo> list = Lists.newArrayList();
        for (CouresOrder info : obj.getRecords()) {
            CourseInfo courseInfo = iCourseInfoService.selectById(info.getCourseInfoId());
            if (courseInfo != null) {
                list.add(courseInfo);
            }
        }
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), list);
    }

    @ApiOperation("课程下架、上架")
    @RequestMapping(value = "/theShelves", method = RequestMethod.POST)
    public ReturnObject theShelves(@ApiParam("课程id") @RequestParam Long id,
                                   @ApiParam("状态（0：上架，3：下架）") @RequestParam Integer auditState) {
        CourseInfo courseRecord = iCourseInfoService.selectById(id);
        if (auditState == 3 && courseRecord.getLiveType() == 1) {
            return new ReturnObject<>(1, "正在上课课程不能下架");
        }
        if (iCouresProgressBillService.judgeCourseStudentProgress(id)) {
            return new ReturnObject<>(1, "学生正在上课课程不能下架");
        }

        CourseInfo courseInfo = new CourseInfo();
        courseInfo.setId(id);
        courseInfo.setAuditState(auditState);
        iCourseInfoService.updateById(courseInfo);
        return new ReturnObject<>(0, "下架成功");
    }


    @ApiOperation("获取老师全部的课程")
    @RequestMapping(value = "/getMyPage", method = RequestMethod.POST)
    public ReturnObject<List<CourseInfo>> getMyPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                    @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                    @ApiParam("状态（0：全部，1：已发布，2：未发布）") @RequestParam(defaultValue = "0") Integer type,
                                                    @ApiParam("上课状态（0：全部，1：授课中，2：即将授课，3：授课结束）") @RequestParam(defaultValue = "0") Integer courseType) {
        EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
        ew.orderBy("info.start_time", false);
        if (type == 1) {
            ew.eq("info.audit_state", 1);
        } else if (type == 2) {
            ew.ne("info.audit_state", 1);
        }
        if (courseType == 1) {
            ew.gt("info.start_time", new Date());
            ew.lt("info.end_time", new Date());
        } else if (courseType == 2) {
            ew.lt("info.start_time", new Date());
        } else if (courseType == 3) {
            ew.gt("info.end_time", new Date());
        }
        ew.andNew().eq("info.user_id", BaseContextHandler.getUserID());
        ew.or().eq("info.crt_user_id", BaseContextHandler.getUserID());

        Page<CourseInfo> obj = iCourseInfoService.selectPage(new Page<>(offset, limit), ew);
        for (CourseInfo info : obj.getRecords()) {
            info.setTaskNum(iCouresTaskService.selectCount(new EntityWrapper<CouresTask>().isNull("p_id").eq(
                    "course_info_id", info.getId())));
        }
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("添加章节学习记录")
    @RequestMapping(value = "/addCourseProgressBill", method = RequestMethod.POST)
    public ReturnObject addCourseProgressBill(@ApiParam("课程id") @RequestParam Long couresId,
                                              @ApiParam("章节id") @RequestParam Long courseChapterId,
                                              @ApiParam("课程播放状态，0：直播中，1：录播，点播") @RequestParam Integer liveType) {
//        @ApiParam("学习状态，0：未学习，1：学习中，2：已学完，默认传2") @RequestParam Integer state
        /*
         * 增加观看记录
         * 直播中课程学习时长：
         *      学习中：课程章节的直播开始时间，当前时间-直播开始时间为学习min数
         *      已学完：课程章节的直播结束时间-直播开始时间为学习min数
         * 录播、点播课程学习时长：
         *      视频播放时间长度
         */
        Integer studyDuration = 0;
        Integer state = 2;
        CourseChapter courseChapter = iCourseChapterService.selectById(courseChapterId);
        if (liveType == 0) {
            Date endTime = new Date();
            if (state == 2) {
                endTime = courseChapter.getEndTime();
            }
            long diff = (endTime.getTime() - courseChapter.getStartTime().getTime()) / (1000 * 60);
            studyDuration = new Long(diff).intValue();
        } else if (liveType == 1) {
            studyDuration = courseChapter.getVideoDuration();
        }
        iCouresProgressBillService.insertCouresProgressBill(couresId, courseChapterId, BaseContextHandler.getUserID(), state, studyDuration);
        return new ReturnObject(0, "添加成功");
    }

    @ApiOperation("删除课程下章节学习记录")
    @RequestMapping(value = "/delCourseProgressBill", method = RequestMethod.POST)
    public ReturnObject delCourseProgressBill(@ApiParam("课程id") @RequestParam Long courseInfoId) {
        EntityWrapper<CouresProgressBill> ew = new EntityWrapper<>();
        ew.eq("user_id", BaseContextHandler.getUserID());
        ew.eq("course_info_id", courseInfoId);
        iCouresProgressBillService.delete(ew);

        return new ReturnObject(0, "删除成功");
    }

    @IgnoreAuth
    @ApiOperation("获取课程详情")
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    public ReturnObject<CourseInfo> getInfo(@ApiParam("id") @RequestParam Long id) {
        CourseInfo courseInfo = iCourseInfoService.selectById(id);
        //获取章节信息
        List<CourseChapter> chapterList = iCourseChapterService.selectList(new EntityWrapper<CourseChapter>().eq(
                "info.course_info_id", id).isNull("info.p_id"));
        courseInfo.setCourseChapterList(chapterList);
        int totalCourseChapter = 0;
        for (CourseChapter courseChapter : courseInfo.getCourseChapterList()) {
            List<CourseChapter> courseChapterList = iCourseChapterService.selectList(
                    new EntityWrapper<CourseChapter>().eq("info.course_info_id", id).eq("info.p_id", courseChapter.getId()));
            totalCourseChapter += courseChapterList.size();
            courseChapter.setCourseChapterList(courseChapterList);
        }
        if (BaseContextHandler.getUserID() != null) {
            //判断是否购买
            courseInfo.setIsBuy(iCouresOrderService.selectCount(new EntityWrapper<CouresOrder>().eq("course_info_id", id).eq("pay_person_id",
                    BaseContextHandler.getUserID()).eq("pay_state", 1)) == 0 ? 0 : 1);

            //课程关注状态
            courseInfo.setFocusCourse(iBaseCollectService.selectCount(new EntityWrapper<BaseCollect>().eq("user_id",
                    BaseContextHandler.getUserID()).eq("type", 2).eq("mold_id", id)) == 0 ? 0 : 1);

            courseInfo.setFocusUser(iBaseFocusService.selectCount(new EntityWrapper<BaseFocus>().eq("user_id",
                    BaseContextHandler.getUserID()).eq("focus_user_id", courseInfo.getUserId())) == 0 ? 0 : 1);
        }
        //获取课程所属机构信息
        BaseOrgan organ = iBaseOrganService.selectOne(new EntityWrapper<BaseOrgan>().eq("user_id", courseInfo.getCrtUserId()).eq("type", 1));
        courseInfo.setOrganInfo(organ);
        //获取课程课件列表
        List<CourseWare> courseWareList = iCourseWareService.selectList(new EntityWrapper<CourseWare>().eq("course_info_id", courseInfo.getId()));
        courseInfo.setCourseWareList(courseWareList);
        //新增课程点击记录
        iCourseClickService.insert(new CourseClick(id, null, BaseContextHandler.getUserID()));

        return new ReturnObject<>(0, totalCourseChapter + "", courseInfo);
    }

    @ApiOperation("举报课程")
    @RequestMapping(value = "/reportCourse", method = RequestMethod.POST)
    public ReturnObject reportCourse(@ApiParam("id") @RequestParam Long id,
                                     @ApiParam("举报内容") @RequestParam String content) {
        //插入举报记录
        BaseFeedback feedback = new BaseFeedback();
        feedback.setCrtTime(new Date());
        feedback.setState(0);
        feedback.setContent(content);
        feedback.setPhone(iBaseAppUserService.selectById(BaseContextHandler.getUserID()).getPhone());
        feedback.setType(2);
        feedback.setReportId(id);
        feedback.setUserId(BaseContextHandler.getUserID());
        iBaseFeedbackService.insert(feedback);
        return new ReturnObject<>(0, "举报成功");
    }

    @ApiOperation("删除课程")
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public ReturnObject del(@ApiParam("id") @RequestParam Long id) {
        iCourseInfoService.deleteById(id);
        return new ReturnObject<>(0, "获取成功");
    }

    @ApiOperation("编辑课程")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public ReturnObject<CourseInfo> edit(@ApiParam("id") @RequestParam Long id,
                                         @ApiParam("课程名称") String name,
                                         @ApiParam("课程类型id") Long courseTypeId,
                                         @ApiParam("价钱（单位：分）") Long amount,
                                         @ApiParam("封面图片地址") String coverImgUrl,
                                         @ApiParam("保存状态（0：保存并发布，3：保存未发布）") Integer auditState,
                                         @ApiParam("是否ios发行（0：不发行，1：发行）") Integer iosRelease,
                                         @ApiParam("简介") String about,
                                         @ApiParam("上课老师id") Long userId,
                                         @ApiParam("课程详情(json存储)") String details,
                                         @ApiParam("1 零基础 2 进阶") Integer level,
                                         @ApiParam("课程类型（0：直播，1：点播）") Integer liveType,
                                         @ApiParam("退款类型（0：课前退，1：7天退款）") Integer refundType,
                                         @ApiParam("章节集合") String chapterModels,
                                         @ApiParam("助教json") String assistant,
                                         @ApiParam("销售json") String sales,
                                         @ApiParam("班级群名称") String className) {
        String typeName = null;
        if (courseTypeId != null) {
            typeName = iCourseTypeService.selectById(courseTypeId).getName();
        }
        CourseInfo courseInfo = new CourseInfo(0, name, userId, courseTypeId, null, null,
                amount, about, details, coverImgUrl, iosRelease, auditState, null, null, level,
                BaseContextHandler.getUserID(), typeName, liveType, refundType, assistant, sales, className, null,
                null, null, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
        courseInfo.setId(id);
        if (liveType == 0) {
            courseInfo.setClassName(name);
            courseInfo.setIntroduce(about);
            courseInfo.setGroupState(0);
        }
        iCourseInfoService.updateById(courseInfo);
        if (StringUtils.isNotBlank(chapterModels)) {
            ChapterListModel chapterListModel = JSONObject.parseObject(chapterModels, ChapterListModel.class);
            //编辑章节
            for (ChapterModel chapterModel : chapterListModel.getChapterModels()) {
                CourseChapter courseChapter = new CourseChapter();
                BeanUtils.copyProperties(chapterModel, courseChapter);
                if (courseChapter.getId() == null) {
                    iCourseChapterService.insert(courseChapter);
                } else {
                    iCourseChapterService.updateById(courseChapter);
                }

                //编辑知识点
                for (KnowledgePointModel knowledgePointModel : chapterModel.getCourseChapterList()) {
                    CourseChapter chapter = new CourseChapter();
                    BeanUtils.copyProperties(knowledgePointModel, chapter);
                    if (chapter.getId() == null) {
                        iCourseChapterService.insert(chapter);
                    } else {
                        iCourseChapterService.updateById(chapter);
                    }
                }
            }
        }
        return new ReturnObject<>(0, "编辑成功", courseInfo);
    }

    @ApiOperation("新增课程")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ReturnObject<CourseInfo> add(@ApiParam("课程名称") @RequestParam String name,
                                        @ApiParam("课程类型id") @RequestParam Long courseTypeId,
                                        @ApiParam("价钱（单位：分）") @RequestParam Long amount,
                                        @ApiParam("封面图片地址") @RequestParam String coverImgUrl,
                                        @ApiParam("保存状态（0：保存并发布，3：保存未发布）") @RequestParam(defaultValue = "0") Integer auditState,
                                        @ApiParam("是否ios发行（0：不发行，1：发行）") @RequestParam(defaultValue = "1") Integer iosRelease,
                                        @ApiParam("简介") @RequestParam String about,
                                        @ApiParam("上课老师id") @RequestParam Long userId,
                                        @ApiParam("课程详情(json存储)") @RequestParam String details,
                                        @ApiParam("1 零基础 2 进阶") @RequestParam(defaultValue = "1") Integer level,
                                        @ApiParam("课程类型（0：直播，1：点播）") @RequestParam(defaultValue = "0") Integer liveType,
                                        @ApiParam("退款类型（0：课前退，1：7天退款）") @RequestParam(defaultValue = "1") Integer refundType,
                                        @ApiParam("章节集合") @RequestParam String chapterModels,
                                        @ApiParam("助教json") String assistant,
                                        @ApiParam("销售json") String sales,
                                        @ApiParam("班级群名称") @RequestParam String className,
                                        @ApiParam("开始时间（yyyy-MM-dd）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                        @ApiParam("结束时间（yyyy-MM-dd）") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) throws Exception {
        ChapterListModel chapterListModel = JSONObject.parseObject(chapterModels, ChapterListModel.class);
        if (liveType == 0) {// 直播课程上课时间筛选
            if (endTime.getTime() < startTime.getTime()) {
                return new ReturnObject<>(1, "课程结束时间不能早于课程开始时间");
            }

            Long upperTime = null;
            for (ChapterModel chapterModel : chapterListModel.getChapterModels()) {
                for (KnowledgePointModel knowledgePointModel : chapterModel.getCourseChapterList()) {
                    if (knowledgePointModel.getEndTime().getTime() < knowledgePointModel.getStartTime().getTime()) {
                        return new ReturnObject<>(1, knowledgePointModel.getName() + "知识点直播结束时间不能早于直播开始时间");
                    }
                    if (upperTime != null && knowledgePointModel.getStartTime().getTime() < upperTime) {
                        return new ReturnObject<>(1, knowledgePointModel.getName() + "知识点直播开始时间不能早于上一节知识点开始时间");
                    }
                    if (knowledgePointModel.getEndTime().getTime() < DateUtil.getSomeMinute(knowledgePointModel.getStartTime(), 30).getTime()) {
                        return new ReturnObject<>(1, knowledgePointModel.getName() + "知识点时长不能小于30分钟");
                    }
                    upperTime = knowledgePointModel.getStartTime().getTime();
                }
            }
        }

        CourseInfo courseInfo = new CourseInfo(0, name, userId, courseTypeId, startTime, endTime,
                amount, about, details, coverImgUrl, iosRelease, auditState, null, null, level,
                BaseContextHandler.getUserID(), iCourseTypeService.selectById(courseTypeId).getName(), liveType,
                refundType, assistant, sales, className, 0, 0, 100, 0D, null, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
        if (liveType == 0) {
            courseInfo.setClassName(name);
            courseInfo.setIntroduce(about);
            courseInfo.setGroupState(0);
        }
        BaseId baseId = iBaseIdService.getNoUseId(2);
        courseInfo.setId(Long.parseLong(baseId.getId() + ""));

        iCourseInfoService.insert(courseInfo);

        baseId.setCourseState(1);
        iBaseIdService.updateById(baseId);

        //创建群组
        GroupMember[] members = {new GroupMember().setId(BaseContextHandler.getUserID().toString())};
        GroupModel group = new GroupModel()
                .setId(courseInfo.getId().toString())
                .setMembers(members)
                .setName(name);
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        Result groupCreateResult = rongCloud.group.create(group);

        int validDuration = 0;
        //新增章节
        for (ChapterModel chapterModel : chapterListModel.getChapterModels()) {
            CourseChapter courseChapter = new CourseChapter();
            BeanUtils.copyProperties(chapterModel, courseChapter);
            courseChapter.setCourseInfoId(courseInfo.getId());
            courseChapter.setUserId(userId);
            courseChapter.setCrtUserId(BaseContextHandler.getUserID());
            iCourseChapterService.insert(courseChapter);
            //新增知识点
            for (KnowledgePointModel knowledgePointModel : chapterModel.getCourseChapterList()) {
                CourseChapter chapter = new CourseChapter();
                BeanUtils.copyProperties(knowledgePointModel, chapter);
                if (knowledgePointModel.getType() == 0) {
                    //直播课程，以直播结束后时间段时间计算
                    chapter.setVideoDuration(0);
                } else {
                    //点播课程，直接上传视频时长
                    validDuration += knowledgePointModel.getVideoDuration();
                    chapter.setVideoDuration(knowledgePointModel.getVideoDuration());
                }
                chapter.setPId(courseChapter.getId());
                chapter.setCourseInfoId(courseInfo.getId());
                chapter.setUserId(userId);
                chapter.setCrtUserId(BaseContextHandler.getUserID());
                iCourseChapterService.insert(chapter);
            }
        }
        //更新课程已录时长
        courseInfo.setValidDuration(validDuration);
        iCourseInfoService.updateById(courseInfo);
        if (groupCreateResult.code == 200) {
            return new ReturnObject<>(0, "新增成功", courseInfo);
        } else {
            return new ReturnObject<>(1, groupCreateResult.getErrorMessage());
        }
    }

    @ApiOperation("开始直播开课")
    @RequestMapping(value = "/startLive", method = RequestMethod.POST)
    public ReturnObject<CreateLive> startLive(@ApiParam("知识点id") @RequestParam Long courseChapterId) throws Exception {

        CourseChapter courseChapter = iCourseChapterService.selectById(courseChapterId);
        courseChapter.setType(1);
        courseChapter.setStartTime(new Date());
        iCourseChapterService.updateById(courseChapter);
        Client cli = new Client(accessKey, secretKey);
        // 生成 RTMP 推流地址
        String url = cli.RTMPPublishURL(publish, hubName, courseChapter.getId().toString(), 43200);
        //创建聊天室
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        rongCloud.chatroom.create(new ChatroomModel[]{new ChatroomModel().setId(courseChapter.getId().toString()).setName
                (courseChapter.getName())});
        return new ReturnObject<>(0, "", new CreateLive(url, courseChapter.getId()));
    }

    @ApiOperation("进入指定房间")
    @RequestMapping(value = "/viewLive", method = RequestMethod.POST)
    public ReturnObject<LiveInfo> viewLive(@ApiParam("知识点id") @RequestParam Long courseChapterId) {
        CourseChapter courseChapter = iCourseChapterService.selectById(courseChapterId);
        if (courseChapter.getCost() == 1) {
            iCouresOrderService.selectCount(new EntityWrapper<CouresOrder>().eq("course_info_id",
                    courseChapter.getCourseInfoId()).eq("user_id", BaseContextHandler.getUserID()).eq("pay_state", 1));
        }
        Client cli = new Client(accessKey, secretKey);
        Hub hub = cli.newHub(hubName);
        //查询直播状态
        try {
            Stream streamA = hub.get(courseChapterId.toString());
            Stream.LiveStatus status = streamA.liveStatus();
        } catch (PiliException e) {
            if (!e.isNotInLive()) {
                e.printStackTrace();
                return new ReturnObject<>(1, "该房间不存在");
            } else {
                //直播中断，修改转播状态
                courseChapter.setType(2);
                courseChapter.setEndTime(new Date());
                iCourseChapterService.updateById(courseChapter);
                return new ReturnObject<>(1, "直播已结束");
            }
        }
        //新增课程点击记录
        iCourseClickService.insert(new CourseClick(courseChapter.getCourseInfoId(), courseChapterId, BaseContextHandler.getUserID()));
        //生成观看地址
        String payUrl = cli.HLSPlayURL(hls, hubName, courseChapterId.toString());
        //主播信息
        UserMobile userMobile = new UserMobile();
        BeanUtils.copyProperties(iBaseAppUserService.selectById(BaseContextHandler.getUserID()),
                userMobile);

        return new ReturnObject<>(0, "", new LiveInfo(payUrl, userMobile));
    }

    @IgnoreAuth
    @ApiOperation("主播关闭推流")
    @RequestMapping(value = "/endLive", method = RequestMethod.POST)
    public ReturnObject endLive(@ApiParam("知识点id") @RequestParam Long courseChapterId) throws Exception {
        CourseChapter courseChapter = iCourseChapterService.selectById(courseChapterId);
        courseChapter.setType(2);
        courseChapter.setEndTime(new Date());
        //直播课程，以直播时间段时间计算
        long diff = (courseChapter.getEndTime().getTime() - courseChapter.getStartTime().getTime()) / (1000 * 60);
        int duration = new Long(diff).intValue();
        courseChapter.setVideoDuration(duration);
        //课程录播时长添加
        CourseInfo courseInfo = iCourseInfoService.selectById(courseChapter.getCourseInfoId());
        courseInfo.setValidDuration(courseInfo.getValidDuration() + duration);
        try {
            //销毁聊天室
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            rongCloud.chatroom.destroy(new ChatroomModel().setId(courseChapterId.toString()));
            //保存直播
            Client cli = new Client(accessKey, secretKey);
            Hub hub = cli.newHub(hubName);
            String url = hub.get(courseChapterId.toString()).save(0, 0);
            courseChapter.setVideoUrl(url);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject<>(1, "直播已结束,保存直播视频失败！");
        }
        iCourseChapterService.updateById(courseChapter);
        iCourseInfoService.updateById(courseInfo);
        return new ReturnObject<>(0, "直播已结束");
    }

    @ApiOperation("获取待审核的课程列表")
    @IgnoreAuth
    @RequestMapping(value = "/getCourses", method = RequestMethod.GET)
    public ReturnObject<List<CourseInfo>> getCourses(@ApiParam("审核状态") Integer auditState) {
        try {
            List<CourseInfo> courseInfos = iCourseInfoService.selectList(new EntityWrapper<CourseInfo>().eq(
                    "audit_state", auditState));
            if (courseInfos != null && courseInfos.size() > 0) {

                return new ReturnObject<>(0, "获取信息成功", courseInfos);
            } else {

                return new ReturnObject<>(1, "暂无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject<>(12, "系统偷懒了");
        }
    }

    @ApiOperation("对课程进行审核")
    @IgnoreAuth
    @RequestMapping(value = "/updateAuditState", method = RequestMethod.GET)
    public ReturnObject updateAuditState(@ApiParam("审核状态") @RequestParam String auditState,
                                         @ApiParam("审核意见") @RequestParam String auditOpinion,
                                         @ApiParam("课程id") @RequestParam String id) {
        try {
            CourseInfo courseInfo = iCourseInfoService.selectById(Long.valueOf(id));
            if (courseInfo != null) {
                courseInfo.setAuditState(Integer.valueOf(auditState));
                courseInfo.setAuditOpinion(auditOpinion);
                courseInfo.setAuditTime(new Date());
                iCourseInfoService.updateById(courseInfo);

                return new ReturnObject(0, "审核成功");
            } else {

                return new ReturnObject(1, "审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }


}

